<?php namespace App\Http\Controllers\Front;

use App\Models\Banners;
use App\Models\Company;
use App\Models\CompanyJobs;
use App\Models\CompanyJobsType;
use App\Models\CompanyDevelop;
use App\Models\CompanyType;
use App\Models\CompanyScale;
use App\Models\CompanyPhoto;
use App\Models\CompanyComment;
use App\Models\Tags;
use App\Models\Area;
use App\Models\Ads;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use App\Models\CompanyInbox;


class CompanyController extends MasterController
{

    /**
     * @var gzxz  工作性质字典
     * 工作性质  0 全职， 1 兼职 ， 2 实习 ，默认0 全职
     */
    protected $gzxz = array();

    /**
     * @var salary 薪资 字典
     * 薪资 0:2k以下；1：2k-5K；2：5k-10k; 3:10k-15k; 4:15k-25k; 5:25k-50k; 6:50k以上 默认0
     */
    protected $salary = array();

    /**
     * @var degree 学历
     * 0：大专；1本科；2:硕士；3：博士；4其它； 默认0
     */
    protected $degree = array();

    /**
     * @var gznx 工作年限
     * 工作年限 0 应届毕业生 1：1年 ； 2：2年 。。。。10：年  ； >10 为10年以上
     */
    protected $gznx = array();

    /**
     * @var status 职位状态 0 未审核  1:审核通过 2:审核不通过; 3:关闭
     */
    protected $status = array();
    protected $ads;         //广告
    protected $nav;         //当前焦点
    protected $areas;       //区域
    protected $types;       //公司类型
    protected $develops;    //发展阶段
    protected $hotjobs;    //紧急招聘
    protected $newjobs;    //最新招聘
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->catgory = CompanyJobsType::where(array('parent_id'=>0))->get();
        $this->gzxz = array(0=>'全职',1=>'兼职',2=>'实习',100=>'不限');
        $this->salary = array(0=>'2k以下',1=>'2k~5k',2=>'5k~10k',3=>'10k~15k',4=>'15k~25k',5=>'25k~50k',6=>'50k以上',100=>'不限');
//         $this->gznx = array(0=>'应届毕业生',1=>'1年',2=>'2年',3=>'3年',4=>'4年',5=>'5年',6=>'6年',7=>'7年',8=>'8年',9=>'9年',10=>'10年',11=>'10年以上',100=>'不限');
        $this->gznx = array(0=>'应届毕业生',1=>'1年以下',2=>'1-3年',3=>'3-5年',4=>'5-10年',5=>'10年以上',100=>'不限');
        $this->degree = array(0=>'大专',1=>'本科',2=>'硕士',3=>'博士',4=>'其他',100=>'不限');
        $this->nav = 3;
        $this->ads = Ads::with(['getPositionName'=>function($query){
                $query->where('alias', '侧面');
            }])->where(['app' => 'enterprise'])->skip(0)->take(3)->get();
        $this->areas = $this->getAreas(40);
        $this->types = CompanyType::where('parent_id','=',0)->orderBy('id','asc')->get();
        $this->develops = CompanyDevelop::orderBy('id','asc')->get();
        //紧急招聘
        $this->hotjobs = CompanyJobs::where('status',1)->orderBy('recruitment','desc')->orderBy('published_at','desc')->orderBy('jobs_id','desc')->skip(0)->take(6)->get();
        //最新招聘
        $this->newjobs = CompanyJobs::where('status',1)->orderBy('updated_at','desc')->orderBy('jobs_id','desc')->skip(0)->take(6)->get();
    }

    /**
     * 企业招聘
     */
    public function index()
    {
        // 职能分类
        $category = CompanyJobsType::where(array('parent_id'=> 0,'display'=>0))->orderBy('sort')->orderBy('created_at')->get();
       //轮播banner图片
       $banner = Banners::where(array('app' => 'company'))->orderBy('sort', 'asc')->orderBy('created_at', 'desc')->skip(0)->take(4)->get();
       //推荐企业
       $companys = Company::orderBy('created_at','desc')->orderBy('id','desc')->skip(0)->take(5)->get();
       //推荐的三级分类
       $recommondCates = array();
       $jobstype = new CompanyJobsType();
       foreach($category as $cate)
       {
            $recommondCates[$cate->cat_id] = $jobstype->recommondChildCates($cate->cat_id);

       }
       //热门职位
        $hotjobs = CompanyJobs::where('status',1)->orderBy('published_at','desc')->orderBy('jobs_id','desc') ->take(12)->get();

        $gznx = $this->gznx;
        $degree = $this->degree;
        $tags = array();
        $types = array();
        foreach ($hotjobs as $key => $val)
        {
             //薪资、学历、工作年限、公司名称、简介、工作区域、主页、发展阶段
            $hotjobs[$key]['gznx_name'] = $gznx[$val->gznx];
            $hotjobs[$key]['degree_name'] = $degree[$val->degree];
            $hotjobs[$key]['area_title'] = $val->areas->title;
            $hotjobs[$key]['com_name'] = $val->company->name;
            $hotjobs[$key]['com_signature'] = $val->company->signature;
            $hotjobs[$key]['com_main_page'] = $val->company->main_page;
            $hotjobs[$key]['develop_name'] = CompanyDevelop::where('id','=',$val->company->develop_id)->pluck('name');

            //公司标签、公司类型 一对多关系
            $tags[$val->company_id] = $jobstype->comTags($val->company_id);
            $types[$val->company_id] = $jobstype->comTypes($val->company_id);

        }

        //热门企业
        $pagesize = 15;
        $skip = 0;
        //发布职位数最多的企业
        $maxCountcoms = $jobstype->maxCountcoms($skip,$pagesize);
        $comdetails = array();
        $comtags = array();
        foreach ($maxCountcoms as $countcom){
            //企业详情
            $comdetails[] = Company::where('id','=',$countcom->company_id)->first();
            foreach ($comdetails as &$val){
             // 热门企业 标签多个、类型一个
             $comtags[$val->id] = $jobstype->comTags($val->id);
             $val['comtype_name'] = $jobstype->comTypeOne($val->id);
           }
        }

        return view('front.company.company')->with('category', $category)
                                    ->with('banners',  $banner)
                                    ->with('company', $companys)
                                    ->with('recommondCates', $recommondCates)
                                    ->with('hotjobs',$hotjobs)
                                    ->with('tags',$tags)
                                    ->with('types',$types)
                                    ->with('comdetail',$comdetails)
                                    ->with('comtags',$comtags)
                                    ->with('jobspages',1)
                                    ->with('nav',$this->nav)
                                    ->with('compages',1);

    }

    /**
     * 职位、企业列表
     */
    public function lists(Request $request)
    {
        $typeid = $request->input('typeid',0);  // 1：职位  2：企业
        switch ($typeid)
        {
            case 1:
                return  $this->jobsList();
            default:
                return  $this->companyList();
        }
    }

    /**
     * 获取职位列表数据
     * @param  $areas 地区
     * @param  $develop 发展阶段
     * @param  $comtype 公司类型
     * @param  $gznx    工作经验
     * @param  $degree  学历
     */
    private function jobsList()
    {
        $keyword = Input::get('kw','');
        $areaid = Input::get('areaid',0);
        $develop = Input::get('develop',0);
        $comtype = Input::get('comtype',0);
        $gznx = Input::get('gznx',100);
        $degree = Input::get('degree',100);
        $gzxz = Input::get('gzxz',100);
        $sort = Input::get('sort',0);
        $page = Input::get('page',0);

        $where = array(
            'areaid'=>$areaid,
            'develop'=>$develop,
            'comtype'=>$comtype,
            'gznx'=>$gznx,
            'degree'=>$degree,
            'gzxz'=>$gzxz,
            'keyword'=>$keyword
        );
        $pagesize = 15;
        $skip = $page * $pagesize;
        $query = new CompanyJobs();
        $jobslist = $query->getJobsList($skip,$pagesize,$where,$sort);
        $jobstype = new CompanyJobsType();
        $comtags = array();
        $comtypes = array();
        $gznxarr = $this->gznx;
        $degreearr = $this->degree;

        if(\Illuminate\Support\Facades\Request::ajax())
        {
            if(count($jobslist)>0)
            {
                foreach ($jobslist as $list)
                {
                    //薪资、学历、工作年限、公司名称、简介、工作区域、主页、发展阶段
//                     $list->salary_name = $salaryarr[$list->salary];
                    $list->gznx_name = $gznxarr[$list->gznx];
                    $list->degree_name = $degreearr[$list->degree];
                    $list->area_title = Area::where('area_id','=',$list->area)->pluck('title');
                    $comdetails = Company::where('id','=',$list->company_id)->first();
                    $list->com_name = $comdetails->name;
                    $list->com_signature = str_limit($comdetails->signature,56);
                    $list->com_main_page = $comdetails->main_page;
                    $list->develop_name = CompanyDevelop::where('id','=',$comdetails->develop_id)->pluck('name')?:'';
                    $list->created_time = date('Y-m-d',strtotime($list->created_at));
                    //公司标签、公司类型 一对多关系
                    $list->tags = $jobstype->comTags($list->company_id);
                    $list->types = $jobstype->comTypes($list->company_id);
                }
                $pages = $page+1;
                if(count($jobslist)<$pagesize){
                        $length = 'falses';
                }else{
                        $length = 'success';
                }
                return Response::json(array('msg'=>'成功',
                        'status'=>'success',
                        'data'=>$jobslist,
                        'length'=>$length,
                        'pages'=>$pages));
            }else{
                return Response::json(array('msg'=>'没有更多数据','status'=>'falses'));
            }
        }else{
            foreach ($jobslist as $list)
            {
                //薪资、学历、工作年限、公司名称、简介、工作区域、主页、发展阶段
//                 $list->salary_name = $salaryarr[$list->salary];
                $list->gznx_name = $gznxarr[$list->gznx];
                $list->degree_name = $degreearr[$list->degree];
                $list->area_title = Area::where('area_id','=',$list->area)->pluck('title');
                $comdetails = Company::where('id','=',$list->company_id)->first();
                $list->com_name = $comdetails->name;
                $list->com_signature = $comdetails->signature;
                $list->com_main_page = $comdetails->main_page;
                $list->develop_name = CompanyDevelop::where('id','=',$comdetails->develop_id)->pluck('name')?:'';
                //公司标签、公司类型 一对多关系
                $comtags[$list->company_id] = $jobstype->comTags($list->company_id);
                $comtypes[$list->company_id] = $jobstype->comTypes($list->company_id);
            }
            return view('front.company.jobslists')
                ->with('nav',$this->nav)
                ->with('areas',$this->areas)
                ->with('develops',$this->develops)
                ->with('types',$this->types)
                ->with('gznxs',$this->gznx)
                ->with('degrees',$this->degree)
                ->with('gzxzs',$this->gzxz)
                ->with('now_area',$areaid)
                ->with('now_develop',$develop)
                ->with('now_type',$comtype)
                ->with('now_gznx',$gznx)
                ->with('now_degree',$degree)
                ->with('now_gzxz',$gzxz)
                ->with('now_sort',$sort)
                ->with('jobslist',$jobslist)
                ->with('comtags',$comtags)
                ->with('comtypes',$comtypes)
                ->with('hotjobs',$this->hotjobs)
                ->with('newjobs',$this->newjobs)
                ->with('ads_img', $this->ads)
                ->with('jobspages',1)
                ->with('comkeyword',$keyword);
        }
    }

    /**
     * 获取企业列表数据
     * @param  $areas 地区
     * @param  $develop 发展阶段
     * @param  $comtype 公司类型
     */
    private function companyList()
    {
        $keyword = Input::get('kw','');
        $areaid = Input::get('areaid',0);
        $develop = Input::get('develop',0);
        $comtype = Input::get('comtype',0);
        $sort = Input::get('sort',0);
        $page = Input::get('page',0);
        $where = array(
            'areaid'=>$areaid,
            'develop'=>$develop,
            'comtype'=>$comtype,
            'keyword'=>$keyword
        );
        $pagesize = 15;
        $skip = $page * $pagesize;
        $query = new Company();
        $comlist = $query->getList($skip, $pagesize, $where,$sort);
        $jobstype = new CompanyJobsType();
        if(\Illuminate\Support\Facades\Request::ajax())
        {
            if(count($comlist)>0)
            {
                foreach ($comlist as $list){
                    // 热门企业 标签多个、类型一个
                    $list->comtags = $jobstype->comTags($list->id);
                    $list->comtype_name = $jobstype->comTypeOne($list->id);
                    $list->com_name = str_limit($list->name,16);
                    $comdetails = Company::where('id','=',$list->id)->first();
                    $list->counts = count($comdetails->jobsinfo);
                }
                $pages = $page+1;
                if(count($comlist)<$pagesize){
                        $length = 'falses';
                }else{
                        $length = 'success';
                }
                return Response::json(array('msg'=>'获取成功',
                        'status'=>'success',
                        'data'=>$comlist,
                        'length'=>$length,
                        'pages'=>$pages));
            }else{
                return Response::json(array('msg'=>'没有更多数据','status'=>'falses'));
            }
        }else{
            $comtags = array();
            foreach ($comlist as $list){
                // 热门企业 标签多个、职位数、类型一个
                $comtags[$list->id] = $jobstype->comTags($list->id);
                $comdetails = Company::where('id','=',$list->id)->first();
                $list->count = count($comdetails->jobsinfo);
                $list->comtype_name = $jobstype->comTypeOne($list->id);
            }
        }
        return view('front.company.comlists')
            ->with('nav',$this->nav)
            ->with('areas',$this->areas)
            ->with('develops',$this->develops)
            ->with('types',$this->types)
            ->with('now_area',$areaid)
            ->with('now_develop',$develop)
            ->with('now_type',$comtype)
            ->with('now_sort',$sort)
            ->with('comlist', $comlist)
            ->with('comtags',$comtags)
            ->with('hotjobs',$this->hotjobs)
            ->with('newjobs',$this->newjobs)
            ->with('ads_img', $this->ads)
            ->with('compages',1)
            ->with('comkeyword',$keyword);
    }


    /**
     * 职位、企业详情
     */
    public function details(Request $request)
    {
        $typeid = $request->input('typeid',0);  // 1：职位  2：企业
        $comid = $request->input('comid',0);
        $jid = $request->input('jobsid',0);
        $jobs = CompanyJobs::with('examination')->find($jid);//获取职位信息
        $cid = ($typeid == 1) ? $jobs->company_id : $comid;
        $company = Company::find($cid);//获取公司信息

        //详细区域地址,规模,公司类型取一个,公司标签取所有
        $company['area_name'] = Area::where('area_id','=',$company->addressinfo->city)->pluck('title');
        $company['address'] = $company->addressinfo->address;
        $company['longitude'] = $company->addressinfo->longitude;
        $company['latitude'] = $company->addressinfo->latitude;
        $company['scale_name'] = CompanyScale::where('id','=',$company->scale_id)->pluck('name');
        $jobstype = new CompanyJobsType();
//        $company['comtype_name'] = $jobstype->comTypeAll($company->id);
        $tagsresult = $company->tags;
        $tags = array();
        foreach ($tagsresult as $res)
        {
            $tags[] = Tags::where('tags_id','=',$res->tags_id)->pluck('tags_name');
        }

        $typesresult = $company->types;
        $types = array();
        foreach ($typesresult as $res)
        {
            $comtype = CompanyType::where('id','=',$res->type_id)->first();
            if(!empty($comtype))
            {
                $types[] =$comtype->name;
            }
        }

        //公司发布的职位信息
//        $jobsresult= $company->jobsinfo;
        $jobsresult= CompanyJobs::where(array('status'=>1,'company_id'=>$cid))->orderBy('updated_at','desc')->orderBy('jobs_id','desc')->get();
        $gzxz = $this->gzxz;
        $salary = $this->salary;
        foreach ($jobsresult as $key => $val)
        {
            $jobsresult[$key]['gzxz_name'] = $gzxz[$val->gzxz];
            $jobsresult[$key]['salary_name'] = $salary[$val->salary];
        }
        //企业或职位评论
        $comments = CompanyComment::with(['childComments'=>function ($query)
            {
              $query->orderBy('created_at','desc');
            }])->where(array('to_comment_id'=>0,'company_id'=>$cid,'job_id'=>$jid))->orderBy('created_at','desc')->get();

        if($typeid == 1){
            if(empty($jobs)){
                abort(404);
            }else{
                //职位信息字段处理
                $gznx = $this->gznx;
                $degree = $this->degree;
                $jobs['gzxz_name'] = $gzxz[$jobs->gzxz];
                $jobs['salary_name'] = $salary[$jobs->salary];
                $jobs['gznx_name'] = $gznx[$jobs->gznx];
                $jobs['degree_name'] = $degree[$jobs->degree];
//                $jobs['sub_catname'] = CompanyJobsType::where('cat_id','=',$jobs->category->parent_id)->pluck('name');
                //相似职位推荐
                $likejobs = CompanyJobs::where('title','like','%'.$jobs->title.'%')->where('company_id','<>',$cid)->where('status',1)->orderBy('recruitment','desc')->orderBy('published_at','desc')->orderBy('jobs_id','desc')->skip(0)->take(6)->get();
                foreach ($likejobs as &$val){
                    $val['salary_name'] = $salary[$val->salary];
                }
                //企业风采  轮播样式
                $photos = CompanyPhoto::where('company_id','=',$cid)->orderBy('updated_at','desc')->orderBy('created_at','desc')->get();
                $questions = collect();
                if(count($jobs->examination)>0)
                {
                    $questions = $jobs->examination->questions;
                }
                $isToDelivery = 0;
                if(!empty($this->user))
                {
                    $inbox = CompanyInbox::where(['company_id'=>$company->id,'job_id'=>$jobs->jobs_id,'user_id'=>$this->user->id])->first();
                    if(!empty($inbox))
                        $isToDelivery = 1;
                }
                return view('front.company.jobsdetails')
                    ->with('nav',$this->nav)
                    ->with('jobs',$jobs)
                    ->with('questions',$questions)
                    ->with('company',$company)
                    ->with('tags',$tags)
                    ->with('types',$types)
                    ->with('isToDelivery',$isToDelivery)
                    ->with('jobslist',$jobsresult)
                    ->with('likejobs',$likejobs)
                    ->with('photos',$photos)
                    ->with('comments',$comments);
            }
        }else{
            if(empty($company)){
                abort(404);
            }else{
                $company->incrementAdd('comments_num',1);
                //企业风采
                $photos = CompanyPhoto::where('company_id','=',$company->id)->orderBy('updated_at','desc')->orderBy('created_at','desc')->skip(0)->take(8)->get();
                //热门企业推荐
                $likecoms = Company::where('id','<>',$company->id)->orderBy('updated_at','desc')->orderBy('auth_at','desc')->orderBy('id','desc')->skip(0)->take(6)->get();
                foreach ($likecoms as &$val){
                    $val['area_middle_name'] = Area::where('area_id','=',$val->addressinfo->city)->pluck('title');
                }
                return view('front.company.comdetails')
                    ->with('nav',$this->nav)
                    ->with('company',$company)
                    ->with('tags',$tags)
                    ->with('types',$types)
                    ->with('jobslist',$jobsresult)
                    ->with('photos',$photos)
                    ->with('likecoms',$likecoms)
                    ->with('comments',$comments);
            }
        }
    }

    /**
     * 地图
     */
    public function baidumap(){
        $cid = Input::get('cid');
        $company = Company::find($cid);//获取公司信息
        $company['area_name'] = Area::where('area_id','=',$company->addressinfo->area)->pluck('title');
        $company['address'] = $company->addressinfo->address;
        $company['longitude'] = $company->addressinfo->longitude;
        $company['latitude'] = $company->addressinfo->latitude;
        return view('front.company.map')->with('company',$company);
    }


    /**
     * 企业招聘  热门职位加载更多 (弃用)
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function moreJobs(Request $request)
    {
        $page = $request->input('page',0);
        $page_size = 7;
        $skip = $page * $page_size;

        $hotjobs = CompanyJobs::where('status',1)->orderBy('published_at','desc')->orderBy('jobs_id','desc')->skip($skip)->take($page_size)->get();
        $jobstype = new CompanyJobsType();
        $salary = $this->salary;
        $gznx = $this->gznx;
        $degree = $this->degree;
        foreach ($hotjobs as &$val)
        {
            //薪资、学历、工作年限、公司名称、简介、工作区域、主页、发展阶段
            $val['salary_name'] = $salary[$val->salary];
            $val['gznx_name'] = $gznx[$val->gznx];
            $val['degree_name'] = $degree[$val->degree];
            $val['area_title'] = $val->areas->title;
            $val['com_name'] = $val->company->name;
            $val['com_sign'] = str_limit($val->company->signature,56);
            $val['com_main_page'] = $val->company->main_page;
            $val['develop_name'] = CompanyDevelop::where('id','=',$val->company->develop_id)->pluck('name');
            $val['created_time'] = date('Y-m-d',strtotime($val->created_at));
            //公司标签、公司类型 一对多关系
            $val['tags'] = $jobstype->comTags($val->company_id);
            $val['types'] = $jobstype->comTypes($val->company_id);
        }

        $pages = $page+1;
        if(count($hotjobs)>0){
            if(count($hotjobs)<$page_size){
                $length = 'falses';
            }else{
                $length = 'success';
            }
            return Response::json(array('msg'=>'成功',
                'status'=>'success',
                'data'=>$hotjobs,
                'length'=>$length,
                'pages'=>$pages));
        }else{
            return Response::json(array('msg'=>'没有更多数据','status'=>'falses'));
        }
    }
    /**
     * 企业招聘  热门企业加载更多 (弃用)
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function moreCompanys(Request $request)
    {
        $page = $request->input('page',0);
        $page_size = 15;
        $skip = $page * $page_size;
        $jobstype = new CompanyJobsType();
        //发布职位数最多的企业
        $maxCountcoms = $jobstype->maxCountcoms($skip,$page_size);
        $comdetails = array();
        foreach ($maxCountcoms as $countcom){
            //企业详情
            $comdetails[] = Company::where('id','=',$countcom->company_id)->first();
            foreach ($comdetails as &$val){
                // 热门企业 标签多个、类型一个
                $val['comtags'] = $jobstype->comTags($val->id);
                $val['comtype_name'] = $jobstype->comTypeOne($val->id);
                $val['counts'] = count($val->jobsinfo);
                $val['com_name'] = str_limit($val->name,12);
            }
        }

        $pages = $page+1;
        if(count($comdetails)>0){
            if(count($maxCountcoms)<$page_size){
                $length = 'falses';
            }else{
                $length = 'success';
            }
            return Response::json(array('msg'=>'获取成功',
                'status'=>'success',
                'data'=>$comdetails,
                'length'=>$length,
                'pages'=>$pages));
        }else{
            return Response::json(array('msg'=>'没有更多数据','status'=>'falses'));
        }
    }

}
